<template>
  <div class="app-container">
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="120px"
      v-loading="loading"
      class="data-form"
    >
      <el-form-item label="K-L分期" prop="klStage">
        <el-radio-group v-model="dataForm.klStage">
          <el-radio border :label="0">（左，L）</el-radio>
          <el-radio border :label="1">（右，R）</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="中医诊断及证型" prop="diagnoseResult">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          show-word-limit
          maxlength="300"
          v-model="dataForm.diagnoseResult"
          placeholder="请输入膝关节骨性关节炎中医诊断及证型"
        ></el-input>
      </el-form-item>

      <hr style="margin-bottom: 40px; margin-left: 50px; margin-top: 50px;" />

      <el-form-item label="本院治疗方式" prop="weTreatmentType">
        <el-checkbox-group v-model="weTreatmentType" @change="weTreatmentTypeChange">
          <el-checkbox-button
            v-for="(item, index) in treatmentTypeList"
            :label="item"
            :key="index"
          >{{item}}</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>

      <transition name="el-zoom-in-top">
        <div v-if="hasDrugTreatment">
          <h3 style="margin-left: 120px; margin-bottom: 30px; color:grey">药物治疗</h3>
          <drug-history :hasContinue="false" ref="drugTreatment"></drug-history>
        </div>
      </transition>

      <transition name="el-zoom-in-top">
        <div v-if="hasNonDrugTreatment">
          <h3 style="margin-left: 120px; margin-bottom: 30px; color:grey">非药物治疗</h3>
          <nonDrug-history :hasContinue="false" ref="nonDrugTreatment"></nonDrug-history>
        </div>
      </transition>

      <transition name="el-zoom-in-top">
        <div v-if="hasOperationTreatment">
          <h3 style="margin-left: 120px; margin-bottom: 30px; color:grey">手术治疗</h3>
          <operation-history ref="operationTreatment"></operation-history>
        </div>
      </transition>
    </el-form>
    <div style="text-align:center">
      <el-button type="primary" @click="prev">上一步</el-button>
      <el-button type="primary" :loading="buttonLoading" @click="saveDataAndExit">保存并退出</el-button>
    </div>
  </div>
</template>

<script>
import DrugHistory from "../history/drug-history";
import NonDrugHistory from "../history/non-drug-history";
import OperationHistory from "../history/operation-history";
import { saveTreatmentInfo, updateTreatmentInfo, queryTreatmentInfo } from "@/api/gonitis/treatmentInfo";
export default {
  components: {
    DrugHistory,
    NonDrugHistory,
    OperationHistory
  },
  data() {
    return {
      // 表单遮罩层
      loading: false,
      buttonLoading: false,
      isDisease: false,
      treatmentTypeList: ["药物治疗", "非药物治疗", "手术治疗"],
      dataForm: {
        id: null,
        diseaseInfoId: null,
        diagnoseResult: "",
        klStage: null
      },
      historyList: {},
      weTreatmentType: [],
      hasDrugTreatment: false,
      hasNonDrugTreatment: false,
      hasOperationTreatment: false,
      dataRule: {
        klStage: [
          {
            required: true,
            message: "K-L分期必须选择",
            trigger: ["blur", "change"]
          }
        ],
        diagnoseResult: [
          {
            required: true,
            message: "膝关节骨性关节炎中医诊断及证型必须输入",
            trigger: "blur"
          }
        ],
        weTreatmentType: [
          {
            validator: (rule, value, callback) => {
              if (
                !this.weTreatmentType ||
                this.weTreatmentType.length === 0
              ) {
                callback(new Error("本院治疗方法必须选择"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  //方法集合
  methods: {
    /** 上一步 */
    prev() {
      if (this.isDisease) {
        this.$parent.active = 0;
      } else {
        this.$parent.active = 1;
      }
    },
    /** 保存并退出 */
    saveDataAndExit() {
      // 先确保当前页面的数组校验
      const flag = this.getAllHistory();
      if (flag == false) {
        // 如果校验失败就直接返回不执行下一步
        return;
      }
      // 然后校验组件内容
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.dataForm.treatmentMap = this.historyList;
          this.buttonLoading = true;
          if (this.dataForm.id) {
            // 更新操作
            updateTreatmentInfo(this.dataForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              // 保存成功后直接跳转到列表页面
              this.goBack();
              // 调用夫方法关闭组件
              this.$emit("close");
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            saveTreatmentInfo(this.dataForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              // 保存成功后直接跳转到列表页面
              this.goBack();
              // 调用夫方法关闭组件
              this.$emit("close");
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 返回列表页面并销毁当前页 */
    goBack() {
      // 关闭当前标签页
      this.$store.dispatch("tagsView/delView", this.$route).then(() => {
        this.$router.push({
          path: "/gonitis/patient/info"
        });
      });
    },
    /** 本院治疗方式改变 */
    weTreatmentTypeChange(value) {
      this.hasDrugTreatment = false;
      this.hasNonDrugTreatment = false;
      this.hasOperationTreatment = false;
      for (let i = 0; i < value.length; i++) {
        if (value[i] === this.treatmentTypeList[0]) {
          this.hasDrugTreatment = true;
        }
        if (value[i] === this.treatmentTypeList[1]) {
          this.hasNonDrugTreatment = true;
        }
        if (value[i] === this.treatmentTypeList[2]) {
          this.hasOperationTreatment = true;
        }
      }
    },
    /** 获取所有历史对象 */
    getAllHistory() {
      if (this.hasDrugTreatment) {
        const drugTreatment = this.$refs.drugTreatment.submit("drugTreatment");
        // 判断通过的话就将koaNonDrugHistory直接放入到集合中
        if (drugTreatment == null) {
          console.log("null3");
          // 如果子组件校验失败就直接返回false
          return false;
        } else {
          // 添加子组件的drugHistory
          this.historyList.drugTreatment = drugTreatment;
        }
      }
      if (this.hasNonDrugTreatment) {
        console.log(this.$refs.nonDrugTreatment);
        const nonDrugTreatment = this.$refs.nonDrugTreatment.submit(
          "nonDrugTreatment"
        );
        // 判断通过的话就将koaNonDrugHistory直接放入到集合中
        if (nonDrugTreatment == null) {
          console.log("null4");
          // 如果子组件校验失败就直接返回false
          return false;
        } else {
          // 添加子组件的drugHistory
          console.log("有值4");
          this.historyList.nonDrugTreatment = nonDrugTreatment;
        }
      }
      if (this.hasOperationTreatment) {
        const operationTreatment = this.$refs.operationTreatment.submit(
          "operationTreatment"
        );
        // 判断通过的话就将koaNonDrugHistory直接放入到集合中
        if (operationTreatment == null) {
          console.log("null5");
          // 如果子组件校验失败就直接返回false
          return false;
        } else {
          // 添加子组件的drugHistory
          console.log("有值5");
          this.historyList.operationTreatment = operationTreatment;
        }
      }
    },
    /** 自动设置diseaseInfoId */
    setDiseaseId() {
      this.dataForm.diseaseInfoId = this.$parent.diseaseInfoId;
      if(this.$parent.updateFlag === 3){
        this.isDisease = true;
      }
    },
    /** 初始化信息 */
    init() {
      const diseaseInfoId = this.dataForm.diseaseInfoId;
      this.loading = true;
      queryTreatmentInfo(diseaseInfoId).then(response => {
        const treatmentInfo = response.data;
        this.dataForm.id = treatmentInfo.id;
        this.dataForm.diagnoseResult = treatmentInfo.diagnoseResult;
        this.dataForm.klStage = treatmentInfo.klStage;
        if (treatmentInfo.drugTreatmentId) {
          this.hasDrugTreatment = true;
          this.weTreatmentType.push(this.treatmentTypeList[0]);
          this.historyList.drugTreatment =
            treatmentInfo.treatmentMap.drugTreatment;
          this.historyList.drugTreatment.id = null;
          this.$nextTick(() => {
            const treatment = this.historyList.drugTreatment;
            this.$refs.drugTreatment.putDrugHistory(treatment);
          });
        }
        if (treatmentInfo.nonDrugTreatmentId) {
          this.hasNonDrugTreatment = true;
          this.weTreatmentType.push(this.treatmentTypeList[1]);
          this.historyList.nonDrugTreatment =
            treatmentInfo.treatmentMap.nonDrugTreatment;
          this.historyList.nonDrugTreatment.id = null;
          this.$nextTick(() => {
            const treatment = this.historyList.nonDrugTreatment;
            this.$refs.nonDrugTreatment.putNonDrugHistory(treatment);
          });
        }
        if (treatmentInfo.operationTreatmentId) {
          this.hasOperationTreatment = true;
          this.weTreatmentType.push(this.treatmentTypeList[2]);
          this.historyList.operationTreatment =
            treatmentInfo.treatmentMap.operationTreatment;
          this.historyList.operationTreatment.id = null;
          this.$nextTick(() => {
            const treatment = this.historyList.operationTreatment;
            this.$refs.operationTreatment.putOperationHistory(treatment);
          });
        }
        
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    }
  },
  /** 生命周期 - 挂载完成（可以访问 DOM 元素） */
  mounted() {
    this.dataForm.diseaseInfoId = this.$parent.diseaseInfoId;
    if (this.$parent.diseaseInfoId) {
      this.dataForm.diseaseInfoId = this.$parent.diseaseInfoId;
      this.isDisease = true;
      this.init();
    }
  }
};
</script>